package com.fz.controller;

import com.fz.entity.WebLogin;
import com.fz.mapper.WebLoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created by Z-C-Y on 2018-03-03.
 * 页面==登录==注册
 */
@Controller
public class WebLoginController {
    @Autowired
    protected WebLoginMapper webLoginMapper;

    /*用户的登录*/
    @RequestMapping(value = "/webpage/login")
    public String webLogin(String userName, String password, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // System.out.println(userName+"===="+password);
        WebLogin user = null;
        if ((userName != null && !"".equals(userName)) && (password != null && !"".equals(password))) {
            user = webLoginMapper.findUserLogin(userName, password);
        }
        if (user != null) {
            HttpSession seesion = request.getSession();
            seesion.setAttribute("userName", user.getName());
            seesion.setAttribute("userId", user.getId());
            return "forward:/webpage/index";

            //  request.getRequestDispatcher("/indexShow").forward(request,response);


        } else {
            request.setAttribute("message", "用户名或者账号错误");

            return "forward:/webpage/login.jsp";/*forward是转发*//*redirect是重定向*/
        }
    }

    /*用户的注册*/
    @RequestMapping(value = "/webpage/register", method = RequestMethod.POST)
    public String addUser(String mobile, String password, String password2, String verifycode, String sendmsg, HttpServletRequest request, HttpServletResponse response) {

        String stu = null;
        String checkstr = (String) request.getSession().getAttribute("checkstr");
        System.out.println(checkstr);
        /*首先判断用户在填写注册信息的时候n某些信息不能为空*/
        if ((mobile != null && !"".equals(mobile))
                && (password != null && !"".equals(password))
                && (password2 != null && !"".equals(password2))
                && (verifycode != null && !"".equals(verifycode))) {

            /*判断两次输入的密码是否相等*/
            if (password.equals(password2)) {
                /*判断输入的验证码是否相同*/
                if (checkstr.equalsIgnoreCase(verifycode)) {
                    /*把数据 存储到数据库中*/
                    webLoginMapper.addUser(mobile, password);

                    stu = "forward:/webpage/login";/*forward是转发*/

                }

            }
        }
        return stu;
    }
}
